﻿if exists (select 1
          from sysobjects
          where  id = object_id('bd_proc_leave_appr_data')
          and type in ('P','PC'))
   drop procedure bd_proc_leave_appr_data
go


CREATE procedure dbo.bd_proc_leave_appr_data (@order_id numeric,@resultStatus numeric,@operator varchar(20)='20000200') as
BEGIN
	--此存储过程适用于请假的审批通过和驳回，


	DECLARE @user_serial numeric--人员
	DECLARE @ishaveedu int--是否是额度假，1：调戏，2：年假
	DECLARE @leave_time int--请假时间,
	
	DECLARE @returnRemark varchar(max) = '' --若单子被拒绝，这个是拒绝原因（多人拒绝，这里是全部人的）

	--1、根据@order_id 获取请假人信息，生成游标
	--2、遍历游标，根据@resultStatus的值，来区分驳回或通过
			--根据游标中的leaveId获取请假类型是调休还是年假	
		--判断处理调休的驳回、通过；年假的驳回、通过
	begin try
		begin tran
			-- 更新驳回原因
			select @returnRemark = (SELECT 
			'('+remark +')'
			FROM
				bd_kq_approvalRecord 
			WHERE
				order_id = @order_id 
				AND approve_key LIKE 'leave%' 
				AND approve_order NOT IN ( 0, 9999 ) 
				AND status = 0
			FOR XML PATH(''))
		--更新单子的取消/驳回原因
		update bd_leave_order 
			set return_remark = @returnRemark
			where order_id = @order_id

		--重新计算
    --驳回后返还假期额度
    IF @resultStatus = 2
    BEGIN
      DECLARE cursor_user CURSOR LOCAL FOR SELECT
        x.user_serial, x.ishaveedu, SUM(x.jsjg)
      FROM (
        SELECT
          l.user_serial, ISNULL(k.ishaveedu, 0) AS ishaveedu, l.jsjg
        FROM lr_kqingj l
      INNER JOIN kt_qingj k ON k.bh = l.bh
        WHERE l.order_id = @order_id AND l.whether_validity = 1
      ) x
      GROUP BY x.user_serial, x.ishaveedu


      OPEN cursor_user
      FETCH NEXT FROM cursor_user INTO @user_serial, @ishaveedu, @leave_time

      --提取第一条数据存放在变量中
      WHILE @@fetch_status = 0
      BEGIN
      --执行重新计算
      --							DECLARE @beginDate DATE
      --							SELECT @beginDate = convert(date,convert(varchar(10),start_date,120)) from bd_leave_order where order_id = @order_id;
      --							EXEC bd_proc_reset_data @beginDate,@ishaveedu,@user_serial,@operator

        EXEC bd_proc_vacation_cancel_order @orderId = @order_id
                                          ,@userIds = ''
                                          ,@operateId = @operator

      FETCH NEXT FROM cursor_user INTO @user_serial, @ishaveedu, @leave_time
      END
    END
    




			--重新计算考勤
			DECLARE @users VARCHAR(MAX) = ''
			DECLARE @startDate DATE
			DECLARE @endDate DATE
		
			SELECT
				@users = @users + CAST(u.user_serial AS VARCHAR(100)) + ','
			FROM (
					select DISTINCT user_serial from lr_kqingj where order_id = @order_id
			) u
			
			SET @users = SUBSTRING(@users,0, LEN(@users))    
			SELECT @startDate = start_date, @endDate = end_date  from bd_leave_order where order_id = @order_id
			EXEC bd_proc_timecard_extend @startDate, @endDate, @users,6
		commit tran
	end try
	begin catch
			DECLARE @errStr VARCHAR(MAX) = ERROR_MESSAGE();
			IF XACT_STATE() <> 0
			BEGIN
			  ROLLBACK TRANSACTION;
			  RAISERROR (@errStr, 16, 1);
				CLOSE cursor_user --关闭游标
				DEALLOCATE cursor_user --释放游标
			END;
	end catch			
		
		

END
GO